from django.shortcuts import render
from rest_framework import status
from rest_framework.generics import ListAPIView, CreateAPIView, UpdateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_extensions.cache.decorators import cache_response
from rest_framework_extensions.cache.mixins import CacheResponseMixin

from areas.models import Area
from areas.serializers import AreaSerializer, AddressSerializer
from users.models import Address, User
from users.serializers import UserDetailSerializer


class AreaView(CacheResponseMixin, ListAPIView):
    '''获取所有省的数据'''
    # 指定查询集，获取所有省的信息
    queryset = Area.objects.filter(parent=None)
    # 指定序列化器
    serializer_class = AreaSerializer


# 使用CacheResponseMixin进行缓存查询，必须放到继承位置的前边
class AreasView(CacheResponseMixin, ListAPIView):
    '''获取所有市和区县的数据'''
    # 指定查询集
    # queryset = Area.objects.get(parent_id=pk)
    # 指定序列化器
    serializer_class = AreaSerializer

    # @cache_response(timeout=60*60, cache='default')
    def get_queryset(self):

        pk = self.kwargs['pk']
        return Area.objects.filter(parent_id=pk)


class AddressView(CreateAPIView, UpdateAPIView, ListAPIView):

    serializer_class = AddressSerializer
    queryset = Address.objects.filter(is_deleted=False)

    # 重写queryset
    # def get_queryset(self):
    #     return Address.objects.filter(is_deleted=False)

    def delete(self, request, pk):
        # 删除收货地址
        address = Address.objects.get(pk=pk)
        address.is_deleted = True
        address.save()

        return Response({'message': 'ok'})


class DefaultAddressView(APIView):

    def put(self, request, pk):
        user = request.user
        user.default_address_id = pk
        user.save()

        return Response({'message': 'ok'}, status=status.HTTP_200_OK)